﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ueEngine.Biz.Inf.LogicEntity;
using ueEngine.Biz.Inf.Entities.DBSupport;
using ueEngine.Biz.Core.ExServer.WorkPool;
using ueEngine.Biz.Core.ExServer.WorkPool.WorkHandle.Email;
using ueEngine.Framework.Common;
using ueEngine.Biz.Inf.Entities;
using ueEngine.Biz.Core.AppService.Member;
using ueEngine.Framework.Exception;
using ueEngine.Biz.Core.ExServer.WorkPool.WorkHandle.FullSearch;
using ueEngine.Biz.Core.ExServer.FullSearch.Core;
using System.Configuration;

namespace ueEngine.Biz.Core.AppService.Recruitment
{
    public class RecruitService
    {
        private string UserName = string.Empty;
        public RecruitService(string userName)
        {
            this.UserName = userName;
        }

        #region 职位申请&简历
        /// <summary>
        /// 查询我申请的兼职
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ItemListBox<RequestSheetModel> QueryOfRequest(int page, int pagesize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.RequestSheet
                            join r in ctx.RecruitSheet
                             on c.RecruitId equals r.Id
                            join p in ctx.Position
                             on c.PositionId equals p.Id
                            orderby c.Id descending
                            where c.UserName == UserName
                            select new
                            {
                                r.Caption,
                                RecruitId = r.Id,
                                p.PositionName,
                                PostionId = p.Id,
                                c.PostDate
                            }).Skip(page * pagesize).Take(pagesize)
                            .ToList()
                            .Select(c => new RequestSheetModel()
                            {
                                RecruitSheet = new RecruitSheetModel()
                                {
                                    Caption = c.Caption,
                                    Id = c.RecruitId
                                },
                                Position = new PositionModel()
                                {
                                    PositionName = c.PositionName,
                                    Id = c.PostionId
                                },
                                PostDate = c.PostDate
                            })
                            .ToList();
                return new ItemListBox<RequestSheetModel>(list).BuildPage(
                    ctx.RequestSheet.Count(c => c.UserName == UserName),
                    page,
                    pagesize);
            }
        }
        public bool RequestJob(RequestSheetModel model)
        {
            var requestSheetModel = new RequestSheetModel();
            requestSheetModel = requestSheetModel.Element(c => c.PositionId == model.PositionId &&
                        c.RecruitId == model.RecruitId &&
                       c.ResumeId == model.ResumeId &&
                       c.UserName == model.UserName);
            if (requestSheetModel == null)
            {
                requestSheetModel = new RequestSheetModel()
                {
                    Message = model.Message,
                    Period = model.Period,
                    PositionId = model.PositionId,
                    PostDate = DateTime.Now,
                    RecruitId = model.RecruitId,
                    ResumeId = model.ResumeId,
                    Salary = model.Salary,
                    UserName = model.UserName,
                    SalaryType = model.SalaryType,
                    Title = model.Title
                };
                try
                {
                    if (requestSheetModel.PostAdd()!= null)
                    {
                        var recruit = new RecruitSheetModel().Element(c => c.Id == model.RecruitId);// new RecruitSheetContext(model.UserName).Entry(model.RecruitId).RecruitSheet;
                        var position = new PositionModel().Element(c => c.Id == model.PositionId);// new PositionContext(model.UserName).Entry(model.PositionId).Position;
                        var firmEmail = new CorporationModel().Element(c => c.Agent == recruit.Recruiter).EMail;// new Firm(recruit.Recruiter).Corporation.Entry().Corporation.EMail;
                        var resume = new ResumeSheetModel().Element(c => c.Id == model.ResumeId);// new ResumeContext(model.UserName).Entry(model.ResumeId).ResumeSheet;
                        if (recruit.EnableEmail)
                        {
                            WorkPool.Append<RequestResumeEmail>(WorkType.email_for_requestresume,
                                new RequestResumeEmail()
                                {
                                    PositionName = position.PositionName,
                                    PublishDate = recruit.PublishDate,
                                    RecuitName = recruit.Caption,
                                    RecuitSheetId = recruit.Id,
                                    Recipient = firmEmail,
                                    AboutMe = resume.AboutMe,
                                    Age = resume.Age.ToString(),
                                    College = resume.College,
                                    CtAddress = resume.Address,
                                    CtEmail = resume.Email,
                                    CtPhone = resume.ContactPhone,
                                    Degree = resume.Degree.Mapping(),
                                    Experience = resume.Experience,
                                    RealName = resume.RealName,
                                    resumeTitle = resume.Title,
                                    Role = resume.Status.Mapping(),
                                    Sex = resume.Gender.Mapping()
                                });
                        }
                    }
                    return true;
                }
                catch (Exception e)
                {
                    LogHelper.Write(CommonLogger.ExServer, LogLevel.Error, e);
                }
                return false;
            }
            return true;

            //using (Context ctx = new Context())
            //{
            //    var any = ctx.RequestSheet.Any(
            //        c => c.PositionId == model.PositionId &&
            //            c.RecruitId == model.RecruitId &&
            //           c.ResumeId == model.ResumeId &&
            //           c.UserName == model.UserName);
            //    if (!any)
            //    {
            //        var item = new RequestSheetModel() {
            //            Message = model.Message,
            //            Period = model.Period,
            //            PositionId = model.PositionId,
            //            PostDate = DateTime.Now,
            //            RecruitId = model.RecruitId,
            //            ResumeId = model.ResumeId,
            //            Salary = model.Salary,
            //            UserName = model.UserName,
            //            SalaryType = model.SalaryType,
            //            Title = model.Title
            //        };
            //        //ctx.RequestSheet.Add(new Inf.Entities.RequestSheet()
            //        //{
            //        //    Message = model.Message,
            //        //    Period = (int)model.Period,
            //        //    PositionId = model.PositionId,
            //        //    PostDate = DateTime.Now,
            //        //    RecruitId = model.RecruitId,
            //        //    ResumeId = model.ResumeId,
            //        //    Salary = model.Salary,
            //        //    UserName = model.UserName,
            //        //    SalaryType = (int)model.SalaryType,
            //        //    Title = model.Title
            //        //});
            //        try
            //        {
            //            if (ctx.SaveChanges() > 0)
            //            {
            //                var recruit = new RecruitSheetModel().Element(c => c.Id == model.RecruitId);// new RecruitSheetContext(model.UserName).Entry(model.RecruitId).RecruitSheet;
            //                var position = new PositionModel().Element(c => c.Id == model.PositionId);// new PositionContext(model.UserName).Entry(model.PositionId).Position;
            //                var firmEmail = new CorporationModel().Element(c => c.Agent == recruit.Recruiter).EMail;// new Firm(recruit.Recruiter).Corporation.Entry().Corporation.EMail;
            //                var resume = new ResumeSheetModel().Element(c => c.Id == model.ResumeId);// new ResumeContext(model.UserName).Entry(model.ResumeId).ResumeSheet;
            //                if (recruit.EnableEmail)
            //                {
            //                    WorkPool.Append<RequestResumeEmail>(WorkType.email_for_requestresume,
            //                        new RequestResumeEmail()
            //                        {
            //                            PositionName = position.PositionName,
            //                            PublishDate = recruit.PublishDate,
            //                            RecuitName = recruit.Caption,
            //                            RecuitSheetId = recruit.Id,
            //                            Recipient = firmEmail,
            //                            AboutMe = resume.AboutMe,
            //                            Age = resume.Age.ToString(),
            //                            College = resume.College,
            //                            CtAddress = resume.Address,
            //                            CtEmail = resume.Email,
            //                            CtPhone = resume.ContactPhone,
            //                            Degree = resume.Degree.Mapping(),
            //                            Experience = resume.Experience,
            //                            RealName = resume.RealName,
            //                            resumeTitle = resume.Title,
            //                            Role = resume.Status.Mapping(),
            //                            Sex = resume.Gender.Mapping()
            //                        });
            //                }
            //            }
            //            return true;
            //        }
            //        catch (Exception e)
            //        {
            //            LogHelper.Write(CommonLogger.ExServer, LogLevel.Error, e);
            //        }
            //        return false;
            //    }
            //    return true;
            //}
        }
        public ItemListBox<ResumeSheetModel> QueryOfResumes(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.ResumeSheet
                            where c.UserName == UserName
                            select c)
                           .ToList()
                           .Select(c => new ResumeSheetModel()
                           {
                               AboutMe = c.AboutMe,
                               ContactPhone = c.ContactPhone,
                               Age = c.Age,
                               Experience = c.Experience,
                               Gender = c.Gender ? Gender.Male : Gender.Female,
                               Id = c.Id,
                               RealName = c.RealName,
                               Status = (SocialRole)c.Status,
                               Title = c.Title,
                               UserName = c.UserName,
                               Address = c.Address,
                               Email = c.EMail,
                               Area = (AreaCode)c.Area,
                               College = c.College,
                               Degree = (Degree)c.Degree
                           }).ToList();
                return new ItemListBox<ResumeSheetModel>(list)
                    .BuildPage(ctx.ResumeSheet.Count(c => c.UserName == UserName), 
                    page, pageSize);
            }
        }
        public ResumeSheetModel NewResume(ResumeSheetModel sheet)
        {
            return sheet.PostAdd();
            //using (Context ctx = new Context())
            //{
            //    var item = ctx.ResumeSheet.Add(new ResumeSheet()
            //    {
            //        AboutMe = sheet.AboutMe,
            //        Age = sheet.Age,
            //        ContactPhone = sheet.ContactPhone,
            //        Experience = sheet.Experience,
            //        Gender = sheet.Gender == Gender.Male,
            //        RealName = sheet.RealName,
            //        Status = (int)sheet.Status,
            //        Title = sheet.Title,
            //        UserName = sheet.UserName,
            //        Address = sheet.Address,
            //        Area = (int)sheet.Area,
            //        EMail = sheet.Email,
            //        College = sheet.College,
            //        Degree = (int)sheet.Degree
            //    });
            //    if (item.PostAdd() > 0)
            //    {
            //        Covariant(item);
            //        return this;
            //    }
            //    return null;
            //}
        }
        public ResumeSheetModel UpdateResume(ResumeSheetModel resumeModel)
        {
            return resumeModel.PostModify();
            //Entry(resumeModel.Id);
            //this.resumeSheet.AboutMe = resumeModel.AboutMe;
            //this.resumeSheet.Age = resumeModel.Age;
            //this.resumeSheet.ContactPhone = resumeModel.ContactPhone;
            //this.resumeSheet.Experience = resumeModel.Experience;
            //this.resumeSheet.Gender = resumeModel.Gender;
            //this.resumeSheet.RealName = resumeModel.RealName;
            //this.resumeSheet.Status = resumeModel.Status;
            //this.resumeSheet.Title = resumeModel.Title;
            //this.resumeSheet.UserName = resumeModel.UserName;
            //if (Inverter(this.resumeSheet).PostModify() > 0)
            //{
            //    return this;
            //}
            //return null;
        }
        public bool DeleteResume(int id)
        {
            using (Context ctx = new Context())
            {
                return ctx.Delete<ResumeSheet>()
                    .WhereSet(c => c.Id, WhereOperator.Equal, id)
                    .And()
                    .WhereSet(c => c.UserName, WhereOperator.Equal, UserName)
                    .End()
                    .Excute() > 0;
            }
        }
        public ResumeSheetModel GetResume(int id)
        {
            return new ResumeSheetModel().Element(c => c.Id == id);
        }
        #endregion

        #region 发布兼职
        /// <summary>
        /// 发布一条新的招募信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RecruitSheetModel NewRecruit(RecruitSheetModel model, PositionPriority peiority = PositionPriority.Normal)
        {
            #region 创建代理企业
            int DepositCompanyId = 0;
            if (model.DepositCompany.Id != 0) //如果通过选择企业创建的企业信息
            {
                var dbModel = new DepositCompanyModel().Element(c => c.Id == model.DepositCompany.Id); //DepositCompany.Entry(model.DepositCompany.Id).Company;

                //如果是以模板创建，但是修改了某些数据
                if (model.DepositCompany.CompanyBusiness != dbModel.CompanyBusiness ||
                    model.DepositCompany.CompanyDetail.NoHTMLLabel().NoSpace() != dbModel.CompanyDetail.NoHTMLLabel().NoSpace() ||
                    model.DepositCompany.CompanyDimensions != dbModel.CompanyDimensions ||
                    model.DepositCompany.CompanyName != dbModel.CompanyName ||
                    model.DepositCompany.CompanyType != dbModel.CompanyType)
                {
                    var depositCompany = new FirmService(string.Empty).CreateDepositCompany(model.DepositCompany, model.Templete);
                    if (depositCompany != null) //如果创建成功
                    {
                        DepositCompanyId = depositCompany.Id; //将招募单的代理企业Id设置为新创建的代理企业Id
                    }
                    else
                    {
                        return null;
                    }
                }
                else //如果是通过选择模板的方式创建，且没有修改任何数据
                {
                    DepositCompanyId = model.DepositCompany.Id;
                }
            }
            else  //如果不是以选择模板的方式创建
            {
                var depositCompany = new FirmService(string.Empty).CreateDepositCompany(model.DepositCompany, model.Templete);// DepositCompany.CreateDepositCompany(model.DepositCompany, model.SaveCompany);
                if (depositCompany != null) //如果创建成功
                {
                    DepositCompanyId = depositCompany.Id; //将招募单的代理企业Id设置为新创建的代理企业Id
                }
                else
                {
                    return null;
                }
            }
            model.DepositCompanyId = DepositCompanyId;//将招募单的代理企业Id设置为新创建的代理企业Id
            #endregion

            model.Refresh = DateTime.Now;
            model.Source = RecruitmentSource.NormalPublish;
            var recruitSheet = model.PostAdd(); // RecruitSheet.CreateRecruitSheet(model.RecruitSheet, model.TempleteThis);//先创建招募单
            if (recruitSheet != null) //如果创建成功
            {
                model.Positions = model.Positions.Select(c =>
                {
                    c.RecruitId = recruitSheet.Id;
                    return c;
                }).ToList(); //为职位的招募单id设置为新添加的招募单id

                foreach (var position in model.Positions)
                {
                    position.PositionDescript = position.PositionDescript.Replace("\r\n", "<br/>");
                    position.PostAdd();
                    //Position.NewPosition(position);
                    //WorkPool.Append<PositionItem>(WorkType.index_position, new PositionItem()
                    //{
                    //    PositionId = position.Id,
                    //    RecuritId = position.RecruitId,
                    //    RecuritType = model.RecruitSheet.RecruitType.Mapping(),
                    //    DepositCompanyName = model.DepositCompany.CompanyName,
                    //    Descript = String.IsNullOrEmpty(position.PositionDescript) ?
                    //        model.RecruitSheet.Description : position.PositionDescript,
                    //    ExpireDate = model.RecruitSheet.Expire,
                    //    MaxSalary = position.MaxSalary,
                    //    MinSalary = position.MinSalary,
                    //    PositionName = position.PositionName,
                    //    PositionType = position.PositionType.Mapping(),
                    //    PublishDate = DateTime.Now,
                    //    SalaryPeriod = position.Period.Mapping(),
                    //    Vacancy = position.Vacancy,
                    //    WorkArea = model.RecruitSheet.WorkArea.Mapping(),
                    //    WorkAddress = model.RecruitSheet.WorkAddress,
                    //    IndexLevel = indexLevel,
                    //    URL = "/home/jobdetail/" + position.Id,
                    //    Priority = peiority
                    //});
                }
                WorkPool.Append<AdvertisementEmail>(WorkType.email_for_advertisement,
                   new AdvertisementEmail()
                   {
                       DisplayName = "要兼职",
                       Title = "有人发布兼职，请尽快审核",
                       Html = String.Format("<b>重庆大学城兼职网，管理员。您好！</b><div>于:{0}有企业会员:{1}，发布了名为：{2}的兼职信息。为了使发布人能尽快进行兼职招募，请即刻对其兼职内容进行审核。</div><div>谢谢</div>",
                        DateTime.Now.ToString(),
                        model.Recruiter,
                        model.Caption),
                       Recipient = ConfigurationManager.AppSettings["adminnotice"]
                   }, null);
                }

            return model;
        }
        public RecruitSheetModel UpdateRecruitment(int Original, RecruitSheetModel model)
        {
            #region 创建代理企业
            int DepositCompanyId = 0;
            if (model.DepositCompany.Id != 0) //如果通过选择企业创建的企业信息
            {
                var dbModel = new DepositCompanyModel().Element(c => c.Id == model.DepositCompany.Id);// DepositCompany.Entry(model.DepositCompany.Id).Company;
                //如果是以模板创建，但是修改了某些数据
                if (model.DepositCompany.CompanyBusiness != dbModel.CompanyBusiness ||
                    model.DepositCompany.CompanyDetail.NoHTMLLabel().NoSpace() != dbModel.CompanyDetail.NoHTMLLabel().NoSpace() ||
                    model.DepositCompany.CompanyDimensions != dbModel.CompanyDimensions ||
                    model.DepositCompany.CompanyName != dbModel.CompanyName ||
                    model.DepositCompany.CompanyType != dbModel.CompanyType)
                {
                    var depositCompany = model.DepositCompany.PostAdd();// DepositCompany.CreateDepositCompany(model.DepositCompany, model.SaveCompany);
                    if (depositCompany != null) //如果创建成功
                    {
                        DepositCompanyId = depositCompany.Id; //将招募单的代理企业Id设置为新创建的代理企业Id
                    }
                    else
                    {
                        return null;
                    }
                }
                else //如果是通过选择模板的方式创建，且没有修改任何数据
                {
                    DepositCompanyId = model.DepositCompany.Id;
                }
            }
            else  //如果不是以选择模板的方式创建
            {
                var depositCompany = model.DepositCompany.PostAdd();// DepositCompany.CreateDepositCompany(model.DepositCompany, model.SaveCompany);
                if (depositCompany != null) //如果创建成功
                {
                    DepositCompanyId = depositCompany.Id; //将招募单的代理企业Id设置为新创建的代理企业Id
                }
                else
                {
                    return null;
                }
            }
            model.DepositCompanyId = DepositCompanyId;//将招募单的代理企业Id设置为新创建的代理企业Id
            #endregion
            model.Refresh = DateTime.Now;
            model.Source = RecruitmentSource.NormalPublish;
            var recruitSheet = model.PostAdd();// RecruitSheet.CreateRecruitSheet(model.RecruitSheet, model.TempleteThis);//先创建招募单
            if (recruitSheet != null) //如果创建成功
            {
                model.Positions = model.Positions.Select(c =>
                {
                    c.RecruitId = recruitSheet.Id;
                    return c;
                }).ToList(); //为职位的招募单id设置为新添加的招募单id

                foreach (var position in model.Positions)
                {
                    position.PostAdd(); // Position.NewPosition(position);
                }
                WorkPool.Append<AdvertisementEmail>(WorkType.email_for_advertisement,
                   new AdvertisementEmail()
                   {
                       DisplayName = "要兼职",
                       Title = "有人发布兼职，请尽快审核",
                       Html = String.Format("<b>重庆大学城兼职网，管理员。您好！</b><div>于:{0}有企业会员:{1}，发布了名为：{2}的兼职信息。为了使发布人能尽快进行兼职招募，请即刻对其兼职内容进行审核。</div><div>谢谢</div>",
                        DateTime.Now.ToString(),
                        model.Recruiter,
                        model.Caption),
                       Recipient = ConfigurationManager.AppSettings["adminnotice"]
                   }, null);

                #region 删除原招募单
                RemoveRecruitment(Original);
                //DeleteOne(Original);
                #endregion
                return model;
            }
            else
            {
                return null;
            }
        }
       /// <summary>
        /// 删除一条招募信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool RemoveRecruitment(int id)
        {
            try
            {
                var recruit = new RecruitSheetModel().Element(c => c.Id == id && c.Recruiter == UserName);// new Inf.Entities.RecruitSheet(id, userName);
                if (recruit.PostDelete() != null)
                {
                    RemovePositionsForRecruitment(recruit.Id);
                    //Position.DeleteAll(recruit.Id);

                    var deposit = new DepositCompanyModel().Element(c => c.Id == recruit.DepositCompanyId);// new Inf.Entities.DepositCompany(recruit.DepositCompanyId);
                    if (!deposit.Templete)
                    {
                        deposit.PostDelete();
                    }
                    return true;
                }
                return false;
            }
            catch (ContextException exp)
            {
                LogHelper.Write(CommonLogger.Zone, LogLevel.Error, exp);
            }
            return false;
        }
        /// <summary>
        /// 获取一条招募信息详情
        /// </summary>
        /// <param name="recruitId"></param>
        /// <returns></returns>
        public RecruitSheetModel GetRecruitment(int recruitId)
        {
            using (Context ctx = new Context())
            {
                var iquery = (from p in ctx.Position
                              join r in ctx.RecruitSheet
                              on p.RecruitId equals r.Id
                              join c in ctx.DepositCompany
                              on r.DepositCompanyId equals c.Id
                              join o in ctx.Corporation
                              on r.Recruiter equals o.Agent
                              where r.Id == recruitId
                              select new
                              {
                                  p = new
                                  {
                                      p.Id,
                                      p.RecruitId,
                                      p.MaxSalary,
                                      p.MinSalary,
                                      p.Period,
                                      p.ScanTime,
                                      p.Vacancy,
                                      p.Degree,
                                      p.Experienced,
                                      p.Gender,
                                      p.PositionDescript,
                                      p.PositionName,
                                      p.PositionType,
                                      p.PositionPriority
                                  },
                                  r = new
                                  {
                                      r.Id,
                                      r.Caption,
                                      //r.Description,
                                      r.RecruitSubject,
                                      r.RecruitType,
                                      r.PublishDate,
                                      r.Contact,
                                      r.ContactPhone,
                                      r.WorkAddress,
                                      r.WorkArea,
                                      r.Recruiter,
                                      r.EnableEmail,
                                      r.ReceiveEmail,
                                      r.QQ,
                                      r.Refresh,
                                      r.IsVerify,
                                      r.MapSetting
                                  },
                                  o = new
                                  {
                                      o.CompanyName,
                                      o.Id,
                                      //o.Identification
                                  },
                                  c = new
                                  {
                                      c.CompanyDetail,
                                      c.CompanyName,
                                      c.Agent,
                                      c.CompanyBusiness,
                                      c.CompanyDimensions,
                                      c.CompanyType,
                                      c.Id
                                  }
                              });
                var data = iquery
                           .GroupBy(o => o.r.Refresh)
                           .ToList()
                           .Select(c => new RecruitSheetModel()
                           {
                               DepositCompany = new DepositCompanyModel()
                               {
                                   Agent = c.FirstOrDefault().c.Agent,
                                   CompanyDetail = c.FirstOrDefault().c.CompanyDetail,
                                   CompanyName = c.FirstOrDefault().c.CompanyName,
                                   Id = c.FirstOrDefault().c.Id,
                                   CompanyBusiness = (Business)c.FirstOrDefault().c.CompanyBusiness,
                                   CompanyDimensions = (CompanyDimensions)c.FirstOrDefault().c.CompanyDimensions,
                                   CompanyType = (CompanyType)c.FirstOrDefault().c.CompanyType
                               },
                               //Description = c.FirstOrDefault().r.Description,
                                   IsVerify = c.FirstOrDefault().r.IsVerify,
                                   Id = c.FirstOrDefault().r.Id,
                                   Caption = c.FirstOrDefault().r.Caption,
                                   RecruitType = (RecruitSheetType)c.FirstOrDefault().r.RecruitType,
                                   RecruitSubject = (RecruitSheetSubject)c.FirstOrDefault().r.RecruitSubject,
                                   PublishDate = c.FirstOrDefault().r.PublishDate,
                                   Refresh = c.FirstOrDefault().r.Refresh,
                                   Contact = c.FirstOrDefault().r.Contact,
                                   ContactPhone = c.FirstOrDefault().r.ContactPhone,
                                   WorkAddress = c.FirstOrDefault().r.WorkAddress,
                                   WorkArea = (AreaCode)c.FirstOrDefault().r.WorkArea,
                                   Recruiter = c.FirstOrDefault().r.Recruiter,
                                   EnableEmail = c.FirstOrDefault().r.EnableEmail,
                                   ReceiveEmail = c.FirstOrDefault().r.ReceiveEmail,
                                   QQ = c.FirstOrDefault().r.QQ,
                                   MapSetting=c.FirstOrDefault().r.MapSetting,
                               AgentInfo=new MemberModel(){
                                   CorporationInfo = new CorporationModel()
                                   {
                                       Id = c.FirstOrDefault().o.Id,
                                       CompanyName = c.FirstOrDefault().o.CompanyName,
                                       //Identification = c.FirstOrDefault().o.Identification
                                   },
                               },
                               Positions = c.Select(o => new PositionModel()
                               {
                                   MaxSalary = o.p.MaxSalary,
                                   MinSalary = o.p.MinSalary,
                                   Period = (SalaryPeriod)o.p.Period,
                                   ScanTime = o.p.ScanTime,
                                   Vacancy = o.p.Vacancy,
                                   Id = o.p.Id,
                                   RecruitId = o.p.RecruitId,
                                   Degree = (Degree)o.p.Degree,
                                   Experienced = o.p.Experienced,
                                   Gender = (Gender)o.p.Gender,
                                   PositionDescript = o.p.PositionDescript,
                                   PositionName = o.p.PositionName,
                                   PositionType = (PositionType)o.p.PositionType,
                                   Priority = (PositionPriority)o.p.PositionPriority
                               }).ToList()
                           }).FirstOrDefault();
                return data;
            }
        }
        /// <summary>
        /// 获取招募单模板
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ItemListBox<RecruitSheetModel> GetTempleteSheetes(int page, int pageSize)
        {
            ItemListBox<RecruitSheetModel> result = new ItemListBox<RecruitSheetModel>();
            result.Data = new List<RecruitSheetModel>();
            using (Context ctx = new Context())
            {
                var data = from c in ctx.RecruitSheet
                           where c.Recruiter == this.UserName && c.Templete
                           select new { c.Id, c.Caption, c.PublishDate };
                result.BuildPage(data.Count(), page, pageSize);
                result.Data = data.ToList().Select(c => new RecruitSheetModel()
                {
                    Id = c.Id,
                    Caption = c.Caption,
                    PublishDate = c.PublishDate
                }).ToList();
            }
            return result;
        }
        /// <summary>
        /// 获取企业模板
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ItemListBox<DepositCompanyModel> GetTempleteCompanies(int page, int pageSize)
        {
            ItemListBox<DepositCompanyModel> result = new ItemListBox<DepositCompanyModel>();
            using (Context ctx = new Context())
            {
                var list = from c in ctx.DepositCompany
                           where c.Agent == this.UserName && c.Templete
                           select new { c.Id, c.CompanyName, c.PostDate };
                result.BuildPage(list.Count(), page, pageSize);
                result.Data = list.ToList().Select(c => new DepositCompanyModel()
                {
                    CompanyName = c.CompanyName,
                    Id = c.Id,
                    PostDate = c.PostDate
                }).ToList();
                return result;
            }
        }
        #endregion

        #region 兼职查询
        /// <summary>
        /// （查询）获得所有已经发布的【招募信息】 （没有地域 职位类型限制）
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="recruitType">Nodefine 为不限</param>
        /// <param name="expireType"></param>
        /// <param name="NoVerify">查询通过管理员认证的兼职信息 false:通过认证的 true：未通过认证的</param>
        /// <param name="anonymity">是否是匿名访问 false:查询当前登录的用户的招聘信息。true：不限查询用户</param>
        /// <returns></returns>
        public ItemListBox<RecruitSheetModel> QueryRecruitment(int page, int pageSize, RecruitSheetType recruitType, bool NoVerify = false, bool anonymity = false)
        {
            ItemListBox<RecruitSheetModel> result = new ItemListBox<RecruitSheetModel>();
            result.Data = new List<RecruitSheetModel>();
            using (Context ctx = new Context())
            {
                var iquery = (from r in ctx.RecruitSheet
                              join d in ctx.DepositCompany
                                 on r.DepositCompanyId equals d.Id
                              join c in ctx.Corporation
                                 on r.Recruiter equals c.Agent
                              join p in ctx.Position
                                on r.Id equals p.RecruitId
                              select new
                              {
                                  RecruitSheet = new
                                  {
                                      r.Id,
                                      r.Caption,
                                      r.Contact,
                                      r.ContactPhone,
                                      //r.Description,
                                      r.PublishDate,
                                      r.Recruiter,
                                      r.RecruitSubject,
                                      r.RecruitType,
                                      r.WorkAddress,
                                      r.WorkArea,
                                      r.IsVerify,
                                      r.Refresh
                                  },
                                  DepositCompany = new { d.Agent, d.CompanyName },
                                  Corporation = new { c.Agent, c.CompanyName },
                                  Positions = new
                                  {
                                      p.Degree,
                                      p.Experienced,
                                      p.Gender,
                                      p.Id,
                                      p.MaxSalary,
                                      p.MinSalary,
                                      p.Period,
                                      p.PositionDescript,
                                      p.PositionName,
                                      p.PositionType,
                                      p.Vacancy,
                                      rqcount = ctx.RequestSheet.Count(q => p.Id == q.PositionId)
                                  },
                              });
                if (recruitType != RecruitSheetType.NoDefine)
                {
                    iquery = iquery.Where(c => c.RecruitSheet.RecruitType == (int)recruitType);
                }
                if (NoVerify)
                {
                    iquery = iquery.Where(c => !c.RecruitSheet.IsVerify);
                }
                else
                {
                    iquery = iquery.Where(c => c.RecruitSheet.IsVerify);
                }
                if (!anonymity)
                {
                    iquery = iquery.Where(c => c.RecruitSheet.Recruiter == UserName);
                }
                var data = iquery.GroupBy(c => c.RecruitSheet.Id)
                               .OrderByDescending(c => c.FirstOrDefault().RecruitSheet.Refresh)
                               .Skip(page * pageSize)
                               .Take(pageSize)
                               .ToList()
                               .Select(c => new RecruitSheetModel()
                               {
                                   AgentInfo = new MemberModel()
                                   {
                                       CorporationInfo = new CorporationModel()
                                       {
                                           Agent = c.FirstOrDefault().Corporation.Agent,
                                           CompanyName = c.FirstOrDefault().Corporation.CompanyName
                                       },
                                   },
                                   DepositCompany = new DepositCompanyModel()
                                   {
                                       Agent = c.FirstOrDefault().DepositCompany.Agent,
                                       CompanyName = c.FirstOrDefault().DepositCompany.CompanyName
                                   },
                                   Id = c.FirstOrDefault().RecruitSheet.Id,
                                   IsVerify = c.FirstOrDefault().RecruitSheet.IsVerify,
                                   Caption = c.FirstOrDefault().RecruitSheet.Caption,
                                   Contact = c.FirstOrDefault().RecruitSheet.Contact,
                                   ContactPhone = c.FirstOrDefault().RecruitSheet.ContactPhone,
                                   //Description = c.FirstOrDefault().RecruitSheet.Description,
                                   PublishDate = c.FirstOrDefault().RecruitSheet.PublishDate,
                                   Recruiter = c.FirstOrDefault().RecruitSheet.Recruiter,
                                   RecruitSubject = (RecruitSheetSubject)c.FirstOrDefault().RecruitSheet.RecruitSubject,
                                   RecruitType = (RecruitSheetType)c.FirstOrDefault().RecruitSheet.RecruitType,
                                   WorkAddress = c.FirstOrDefault().RecruitSheet.WorkAddress,
                                   WorkArea = (AreaCode)c.FirstOrDefault().RecruitSheet.WorkArea,

                                   Positions = c.Select(p => new PositionModel()
                                   {
                                       Degree = (Degree)p.Positions.Degree,
                                       Experienced = p.Positions.Experienced,
                                       Gender = (Gender)p.Positions.Gender,
                                       Id = p.Positions.Id,
                                       MaxSalary = p.Positions.MaxSalary,
                                       MinSalary = p.Positions.MinSalary,
                                       Period = (SalaryPeriod)p.Positions.Period,
                                       PositionDescript = p.Positions.PositionDescript,
                                       PositionName = p.Positions.PositionName,
                                       PositionType = (PositionType)p.Positions.PositionType,
                                       Vacancy = p.Positions.Vacancy,
                                       ItemCountOfRequestSheet = p.Positions.rqcount
                                   }).ToList()
                               }).ToList();

                int itemCount = 0;
                var itemCountQuery = ctx.RecruitSheet
                                   .Select(c => new { c.Recruiter, c.IsVerify, c.Id });
                if (NoVerify)
                {
                    itemCountQuery = itemCountQuery.Where(c => !c.IsVerify);
                }
                else
                {
                    itemCountQuery = itemCountQuery.Where(c => c.IsVerify);
                }
                if (!anonymity)
                {
                    itemCountQuery = itemCountQuery
                                   .Where(c => c.Recruiter == UserName);
                }
                itemCount = itemCountQuery.Count();

                result = new ItemListBox<RecruitSheetModel>(data);
                result.BuildPage(itemCount, page, pageSize);
                return result;
            }
        }
        public ItemListBox<RecruitSheetModel> QueryRecruitment(int page, int pagesize, RecruitSheetType recruitSheetType, RecruitSheetSubject recruitSheetSubject)
        {
            using (Context ctx = new Context())
            {
                var query = from p in ctx.Position
                            join r in ctx.RecruitSheet
                                on p.RecruitId equals r.Id
                            join c in ctx.DepositCompany
                                on r.DepositCompanyId equals c.Id
                            where r.IsVerify
                            select new { p, r, c };
                if (recruitSheetType != RecruitSheetType.NoDefine)
                {
                    query = query.Where(c => c.r.RecruitType == (int)recruitSheetType);
                }
                if (recruitSheetSubject != RecruitSheetSubject.Default)
                {
                    query = query.Where(c => c.r.RecruitSubject == (int)recruitSheetSubject);
                }
                int itemCount = query.Count();
                var data = query.GroupBy(c => c.r.Id)
                    .OrderByDescending(c => c.FirstOrDefault().r.Refresh)
                    .Skip(page * pagesize)
                    .Take(pagesize)
                    .ToList()
                    .Select(c => new RecruitSheetModel()
                    {
                        Id = c.Key,
                        QQ = c.FirstOrDefault().r.QQ,
                        Caption = c.FirstOrDefault().r.Caption,
                        Contact = c.FirstOrDefault().r.Contact,
                        ContactPhone = c.FirstOrDefault().r.ContactPhone,
                        PublishDate = c.FirstOrDefault().r.PublishDate,
                        Refresh = c.FirstOrDefault().r.Refresh,
                        ReceiveEmail = c.FirstOrDefault().r.ReceiveEmail,
                        RecruitType = (RecruitSheetType)c.FirstOrDefault().r.RecruitType,
                        WorkArea = (AreaCode)c.FirstOrDefault().r.WorkArea,
                        WorkAddress = c.FirstOrDefault().r.WorkAddress,
                        Positions = c.Select(p => new PositionModel()
                        {
                            Degree = (Degree)p.p.Degree,
                            Experienced = p.p.Experienced,
                            Gender = (Gender)p.p.Gender,
                            MinSalary = p.p.MinSalary,
                            MaxSalary = p.p.MaxSalary,
                            Period = (SalaryPeriod)p.p.Period,
                            PositionDescript = p.p.PositionDescript,
                            PositionName = p.p.PositionName,
                            PositionType = (PositionType)p.p.PositionType,
                            Vacancy = p.p.Vacancy,
                            Id = p.p.Id
                        }).ToList(),
                        DepositCompany = new DepositCompanyModel()
                        {
                            CompanyName = c.FirstOrDefault().c.CompanyName,
                            CompanyBusiness = (Business)c.FirstOrDefault().c.CompanyBusiness,
                            CompanyDetail = c.FirstOrDefault().c.CompanyDetail,
                            CompanyDimensions = (CompanyDimensions)c.FirstOrDefault().c.CompanyDimensions,
                            CompanyType = (CompanyType)c.FirstOrDefault().c.CompanyType
                        }
                    })
                    .ToList();
                return new ItemListBox<RecruitSheetModel>(data).BuildPage(itemCount, page, pagesize);
            }
        }
        public ItemListBox<RecruitSheetModel> QueryRecruitment(int page, int pagesize, RecruitSheetType recruitSheetType, AreaCode areaCode, PositionType positionType)
        {
            using (Context ctx = new Context())
            {
                var query = from p in ctx.Position
                            join r in ctx.RecruitSheet
                                on p.RecruitId equals r.Id
                            join c in ctx.DepositCompany
                                on r.DepositCompanyId equals c.Id
                            where r.IsVerify
                            orderby r.Refresh descending
                            select new { p, r, c };
                if (recruitSheetType != RecruitSheetType.NoDefine)
                {
                    query = query.Where(c => c.r.RecruitType == (int)recruitSheetType);
                }
                if (areaCode != AreaCode.NoDefine)
                {
                    query = query.Where(c => c.r.WorkArea == (int)areaCode);
                }
                if (positionType != PositionType.NoDefine)
                {
                    query = query.Where(c => c.p.PositionType == (int)positionType);
                }
                int itemCount = query.Count();
                var data = query.GroupBy(c => c.r.Id)
                    .Skip(page * pagesize)
                    .Take(pagesize)
                    .ToList()
                    .Select(c => new RecruitSheetModel()
                    {
                        QQ = c.FirstOrDefault().r.QQ,
                        Caption = c.FirstOrDefault().r.Caption,
                        Contact = c.FirstOrDefault().r.Contact,
                        ContactPhone = c.FirstOrDefault().r.ContactPhone,
                        PublishDate = c.FirstOrDefault().r.PublishDate,
                        ReceiveEmail = c.FirstOrDefault().r.ReceiveEmail,
                        RecruitType = (RecruitSheetType)c.FirstOrDefault().r.RecruitType,
                        WorkArea = (AreaCode)c.FirstOrDefault().r.WorkArea,
                        WorkAddress = c.FirstOrDefault().r.WorkAddress,
                        Positions = c.Select(p => new PositionModel()
                        {
                            Degree = (Degree)p.p.Degree,
                            Experienced = p.p.Experienced,
                            Gender = (Gender)p.p.Gender,
                            MinSalary = p.p.MinSalary,
                            MaxSalary = p.p.MaxSalary,
                            Period = (SalaryPeriod)p.p.Period,
                            PositionDescript = p.p.PositionDescript,
                            PositionName = p.p.PositionName,
                            PositionType = (PositionType)p.p.PositionType,
                            Vacancy = p.p.Vacancy
                        }).ToList(),
                        DepositCompany = new DepositCompanyModel()
                        {
                            CompanyName = c.FirstOrDefault().c.CompanyName,
                            CompanyBusiness = (Business)c.FirstOrDefault().c.CompanyBusiness,
                            CompanyDetail = c.FirstOrDefault().c.CompanyDetail,
                            CompanyDimensions = (CompanyDimensions)c.FirstOrDefault().c.CompanyDimensions,
                            CompanyType = (CompanyType)c.FirstOrDefault().c.CompanyType
                        }
                    })
                    .ToList();
                return new ItemListBox<RecruitSheetModel>(data).BuildPage(itemCount, page, pagesize);
            }
        }  
        ///// <summary>
        ///// 按照招募单类型查询审核通过的【职位信息】
        ///// </summary>
        ///// <param name="page"></param>
        ///// <param name="pagesize"></param>
        ///// <param name="type"></param>
        ///// <param name="orderby"></param>
        ///// <returns></returns>
        //public ItemListBox<PositionModel> QueryPosition(int page, int pagesize, RecruitSheetType type, OrderBySet orderby)
        //{
        //    ItemListBox<PositionModel> result = new ItemListBox<PositionModel>()
        //    {
        //        Data = new List<PositionModel>()
        //    };
        //    using (Context ctx = new Context())
        //    {
        //        var query = (from c in ctx.RecruitSheet
        //                     join p in ctx.Position
        //                     on c.Id equals p.RecruitId
        //                     where c.IsVerify && c.RecruitType == (int)type
        //                     select new { p, c.Refresh, c.WorkArea, c.Caption, c.PublishDate });
        //        int itemCount = query.Count();
        //        switch (orderby)
        //        {
        //            case OrderBySet.DateAsc:
        //                query = query.OrderBy(c => c.Refresh);
        //                break;
        //            case OrderBySet.DateDesc:
        //                query = query.OrderByDescending(c => c.Refresh);
        //                break;
        //            case OrderBySet.MinSalaryAsc:
        //                query = query.OrderBy(c => c.p.MinSalary * (int)c.p.Period); //按照最高的一个最低月薪岗位作为排序依据
        //                break;
        //            case OrderBySet.MinSalaryDesc:
        //                query = query.OrderByDescending(c => c.p.MinSalary * (int)c.p.Period); //按照最高的一个最低月薪岗位作为排序依据
        //                break;
        //            case OrderBySet.MaxSalaryAsc:
        //                query = query.OrderBy(c => c.p.MaxSalary * (int)c.p.Period); //按照最高的一个最高月薪岗位作为排序依据
        //                break;
        //            case OrderBySet.MaxSalaryDesc:
        //                query = query.OrderByDescending(c => c.p.MaxSalary * (int)c.p.Period); //按照最高的一个最高月薪岗位作为排序依据
        //                break;
        //            case OrderBySet.AvgSalaryAsc:
        //                query = query.OrderBy(c => (c.p.MaxSalary + c.p.MinSalary) * (int)c.p.Period / 2); //按照最高的一个最高月薪岗位作为排序依据
        //                break;
        //            case OrderBySet.AvgSalaryDesc:
        //                query = query.OrderByDescending(c => (c.p.MaxSalary + c.p.MinSalary) * (int)c.p.Period / 2); //按照最高的一个最高月薪岗位作为排序依据
        //                break;
        //        }
        //        result.Data = query.Skip(page * pagesize)
        //                    .Take(pagesize)
        //                    .ToList()
        //                    .Select(c => new PositionModel()
        //                    {
        //                        PositionName = c.p.PositionName,
        //                        Id = c.p.Id,
        //                        RecruitId = c.p.RecruitId,
        //                        Priority = (PositionPriority)c.p.PositionPriority,
        //                        RecruitSheet = new RecruitSheetModel()
        //                        {
        //                            WorkArea = (AreaCode)c.WorkArea,
        //                            Caption = c.Caption,
        //                            PublishDate = c.PublishDate
        //                        }
        //                    })
        //                    .ToList();
        //        result.BuildPage(itemCount, page, pagesize);
        //        return result;
        //    }
        //}
        /// <summary>
        /// 按照招募单类型查询所有审核通过的，符合地域、职位类型限制的(如果是不限，则不加地域和职位类型条件)【职位信息】发布时间倒序
        /// </summary>
        /// <param name="rt"></param>
        /// <param name="areaCode"></param>
        /// <param name="positionType"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ItemListBox<PositionModel> QueryPosition(int page, int pageSize, RecruitSheetType rt,RecruitSheetSubject subject, AreaCode areaCode, PositionType positionType, string agent)
        {
            ItemListBox<PositionModel> result = null;
            string key = string.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}",
                page,
                pageSize,
                (int)rt,
                (int)subject,
                (int)areaCode,
                (int)positionType,
                agent);
            result = ueEngine.Framework.Caching.ueCache.GetCache<ItemListBox<PositionModel>>(key);
            if (result == null)
            {
                result = QueryPositionReal(page, pageSize, rt,subject, areaCode, positionType, agent);
                if (result != null)
                {
                    ueEngine.Framework.Caching.ueCache.Add<ItemListBox<PositionModel>>(key, result, Framework.Caching.CacheExpireStrategy.Sliding, new TimeSpan(0, 10, 0));
                }
            }
            return result;
        }

        private ItemListBox<PositionModel> QueryPositionReal(int page, int pageSize, RecruitSheetType rt,RecruitSheetSubject subject, AreaCode areaCode, PositionType positionType, string agent)
        {
            ItemListBox<PositionModel> result = new ItemListBox<PositionModel>()
            {
                Data = new List<PositionModel>()
            };
            using (Context ctx = new Context())
            {
                var query = (from c in ctx.RecruitSheet
                             join p in ctx.Position
                             on c.Id equals p.RecruitId
                             join d in ctx.DepositCompany
                             on c.DepositCompanyId equals d.Id
                             join cop in ctx.Corporation
                             on c.Recruiter equals cop.Agent
                             where c.IsVerify
                             orderby c.Refresh descending
                             select new
                             {
                                 p,
                                 c.Recruiter,
                                 c.PublishDate,
                                 c.Refresh,
                                 c.Caption,
                                 c.RecruitType,
                                 c.RecruitSubject,
                                 c.WorkArea,
                                 c.WorkAddress,
                                 cop.CertificationLevel,
                                 //c.Description,
                                 d.CompanyName
                             });
                if (!String.IsNullOrEmpty(agent))
                {
                    query = query.Where(c => c.Recruiter == agent);
                }
                if (rt != RecruitSheetType.NoDefine)
                {
                    query = query.Where(c => c.RecruitType == (int)rt);
                }
                if (subject != RecruitSheetSubject.Default)
                {
                    query = query.Where(c => c.RecruitSubject == (int)subject);
                }
                if (areaCode != AreaCode.NoDefine)
                {
                    query = query.Where(c => c.WorkArea == (int)areaCode);
                }
                if (positionType != PositionType.NoDefine)
                {
                    query = query.Where(c => c.p.PositionType == (int)positionType);
                }
                int itemCount = query.Count();
                result.Data = query.Skip(page * pageSize)
                            .Take(pageSize)
                            .ToList()
                            .Select(c => new PositionModel()
                            {
                                Degree = (Degree)c.p.Degree,
                                RecruitSheet = new RecruitSheetModel()
                                {
                                    WorkArea = (AreaCode)c.WorkArea,
                                    Caption = c.Caption,
                                    Refresh = c.Refresh,
                                    //Description = c.Description,
                                    WorkAddress = c.WorkAddress,
                                    PublishDate = c.PublishDate,
                                    Id = c.p.RecruitId,
                                    RecruitSubject = (RecruitSheetSubject)c.RecruitSubject
                                },
                                DepositCompany = new DepositCompanyModel()
                                {
                                    CompanyName = c.CompanyName
                                },
                                Experienced = c.p.Experienced,
                                Gender = (Gender)c.p.Gender,
                                Id = c.p.Id,
                                MaxSalary = c.p.MaxSalary,
                                MinSalary = c.p.MinSalary,
                                Period = (SalaryPeriod)c.p.Period,
                                PositionDescript = c.p.PositionDescript,
                                PositionName = c.p.PositionName,
                                PositionType = (PositionType)c.p.PositionType,
                                Priority = (PositionPriority)c.p.PositionPriority,
                                PositionLevel = (PositionLevel)c.p.PositionLevel,
                                RecruitId = c.p.RecruitId,
                                Vacancy = c.p.Vacancy,
                                
                                CertificationLevel = (Inf.LogicEntity.CertificationLevel)c.CertificationLevel
                            })
                            .ToList();
                result.BuildPage(itemCount, page, pageSize,new PageParameter(){
                    IsActive = true,
                    Script="setpage({0});OnPost();"
                });
                return result;
            }
        }
        /// <summary>
        /// 操作一个求职申请
        /// </summary>
        /// <param name="resumeid">RequestSheetID</param>
        /// <param name="controlType">操作方式0：录用，1：拒绝</param>
        /// <returns>录用或拒绝结果</returns>
        public int ControlResume(int requestSheetId, int controlType)
        {
            using (Context ctx = new Context())
            {
                var item = new RequestSheetModel().Element(c => c.Id == requestSheetId);
                if (item != null)
                {
                    if (controlType == 0)
                    {
                        item.State =  RequestState.Nod;
                    }
                    else if (controlType == 1)
                    {
                        item.State =  RequestState.Refuse;
                    }
                    else
                    {
                        return -1;
                    }
                    if (item.PostModify() != null)
                    {
                        return controlType;
                    }
                }
                return -1;
            }
        }
        #endregion

        #region 职位
        public PositionModel NewPosition(PositionModel model)
        {
            if (model.PostAdd() != null)
            {
                return model;
            }
            return null;
        }
        /// <summary>
        /// 删除指定招募单下的所有职位信息
        /// </summary>
        /// <param name="recruitId"></param>
        public bool RemovePositionsForRecruitment(int recruitId)
        {
            using (Context ctx = new Context())
            {
                return ctx.Delete<Position>()
                    .WhereSet(c => c.RecruitId, WhereOperator.Equal, recruitId)
                    .End()
                    .Excute() > 0;
            }
        }
        public PositionModel PositionDetail(int positionId)
        {
            using (Context ctx = new Context())
            {
                var position = (from c in ctx.Position
                                join r in ctx.RecruitSheet
                                on c.RecruitId equals r.Id
                                join d in ctx.DepositCompany
                                on r.DepositCompanyId equals d.Id
                                where c.Id == positionId
                                select new
                                {
                                    Position = c,
                                    CompanyName = d.CompanyName,
                                    RecruitTitle = r.Caption
                                }).FirstOrDefault();
                if (position != null)
                {
                    return new PositionModel()
                    {
                        Degree = (Degree)position.Position.Degree,
                        DepositCompany = new DepositCompanyModel()
                        {
                            CompanyName = position.CompanyName
                        },
                        RecruitSheet = new RecruitSheetModel()
                        {
                            Caption = position.RecruitTitle
                        },
                        Experienced = position.Position.Experienced,
                        Gender = (Gender)position.Position.Gender,
                        Id = position.Position.Id,
                        MaxSalary = position.Position.MaxSalary,
                        MinSalary = position.Position.MinSalary,
                        Period = (SalaryPeriod)position.Position.Period,
                        PositionDescript = position.Position.PositionDescript,
                        PositionName = position.Position.PositionName,
                        PositionType = (PositionType)position.Position.PositionType,
                        RecruitId = position.Position.RecruitId
                    };
                }
                return null;
            }
        }
        /// <summary>
        /// 查询职位详情
        /// </summary>
        /// <param name="positionId"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PositionModel PositionDetail(int positionId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var position = (from c in ctx.Position
                                join i in ctx.RecruitSheet
                                    on c.RecruitId equals i.Id
                                join r in ctx.RequestSheet
                                   on c.Id equals r.PositionId into g
                                where c.Id == positionId
                                from p in g.DefaultIfEmpty()
                                select new
                                {
                                    postion = c,
                                    recruitSheet = new { i.WorkArea, i.IsVerify },
                                    requestsheet = p == null ? null : p
                                })
                                 .OrderBy(c => c.requestsheet.Id)
                                 .Skip(page * pageSize)
                                 .Take(pageSize)
                                 .ToList()
                                 .GroupBy(c => c.postion.Id)
                                 .Select(c => new PositionModel()
                                 {
                                     Degree = (Degree)c.FirstOrDefault().postion.Degree,
                                     Experienced = c.FirstOrDefault().postion.Experienced,
                                     Gender = (Gender)c.FirstOrDefault().postion.Gender,
                                     Id = c.FirstOrDefault().postion.Id,
                                     MaxSalary = c.FirstOrDefault().postion.MaxSalary,
                                     MinSalary = c.FirstOrDefault().postion.MinSalary,
                                     Period = (SalaryPeriod)c.FirstOrDefault().postion.Period,
                                     PositionDescript = c.FirstOrDefault().postion.PositionDescript,
                                     PositionName = c.FirstOrDefault().postion.PositionName,
                                     PositionType = (PositionType)c.FirstOrDefault().postion.PositionType,
                                     RecruitId = c.FirstOrDefault().postion.RecruitId,
                                     ScanTime = c.FirstOrDefault().postion.ScanTime,
                                     Trusteeship = c.FirstOrDefault().postion.Trusteeship,
                                     Vacancy = c.FirstOrDefault().postion.Vacancy,
                                     RecruitSheet = new RecruitSheetModel()
                                     {
                                         WorkArea = (AreaCode)c.FirstOrDefault().recruitSheet.WorkArea,
                                         IsVerify = c.FirstOrDefault().recruitSheet.IsVerify,
                                     },
                                     RequestSheetes = new ItemListBox<RequestSheetModel>(c.Select(o => o.requestsheet == null ?
                                        null :
                                        new RequestSheetModel()
                                        {
                                            Id = o.requestsheet.Id,
                                            Message = o.requestsheet.Message,
                                            Period = (SalaryPeriod)o.requestsheet.Period,
                                            ResumeId = o.requestsheet.ResumeId,
                                            Salary = o.requestsheet.Salary,
                                            State = (RequestState)o.requestsheet.State,
                                            UserName = o.requestsheet.UserName,
                                            PositionId = o.requestsheet.PositionId,
                                            RecruitId = o.requestsheet.RecruitId,
                                            PostDate = o.requestsheet.PostDate,
                                            Title = o.requestsheet.Title
                                        }).ToList())
                                 }).FirstOrDefault();

                int itemCount = ctx.RequestSheet.Where(c => c.PositionId == positionId).Count();
                position.RequestSheetes.BuildPage(itemCount, page, pageSize);
                return position;
            }
        }
        public ItemListBox<PositionCell> PositionSearch(string key, RecruitSheetType recruitType,RecruitSheetSubject recruitSubject, AreaCode areaCode, PositionType positionType, string agent, int page, int pageSize)
        {
            int itemCount = 0;
            var result = new PositionIndex().Search(key, recruitType,recruitSubject, areaCode, positionType, agent, pageSize, page + 1, out itemCount);
            return new ItemListBox<PositionCell>(result).BuildPage(itemCount, page, pageSize, new PageParameter()
            {
                IsActive = true,
                Script = "setpage({0});OnPost();"
            });
        }

        #endregion

        #region 关注
        /// <summary>
        /// 获得所关注的企业
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ItemListBox<RecruiterCollectModel> QueryOfCollect(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.RecruiterCollect
                            join o in ctx.Corporation
                             on c.Agent equals o.Agent
                            where c.Seeker == UserName
                            orderby c.Id descending
                            select new
                            {
                                c.Id,
                                c.AddDate,
                                c.Agent,
                                Corporation = new
                                {
                                    o.CompanyName,
                                    //o.Identification,
                                    o.Id
                                }
                            })
                            .Skip(page * pageSize)
                            .Take(pageSize)
                            .ToList()
                            .Select(c => new RecruiterCollectModel()
                            {
                                AddDate = c.AddDate,
                                Agent = c.Agent,
                                Id = c.Id,
                                Seeker = UserName,
                                CorporationModel = new CorporationModel()
                                {
                                    CompanyName = c.Corporation.CompanyName,
                                    //Identification = c.Corporation.Identification,
                                    Id = c.Corporation.Id
                                }
                            })
                            .ToList();
                return new ItemListBox<RecruiterCollectModel>(list).BuildPage(
                    ctx.RecruiterCollect.Count(c => c.Seeker == UserName),
                    page,
                    pageSize);
            }
        }
        public bool RemoveRecruiterCollect(int id)
        {
            using (Context ctx = new Context())
            {
                return ctx.Delete<RecruiterCollect>()
                    .WhereSet(c => c.Id, WhereOperator.Equal, id)
                    .End()
                    .Excute() > 0;
            }
        }
        #endregion    

        #region 人才关注
        public TalentModel NewTalent(int resumeId)
        {
            using (Context ctx = new Context())
            {
                var item = new TalentModel().Element(c => c.ResumeId == resumeId);// ctx.Talent.FirstOrDefault(c => c.ResumeId == resumeId);
                if (item != null)
                {
                    return item;
                }
                return new TalentModel()
                {
                    Recruiter = UserName,
                    ResumeId = resumeId
                }.PostAdd();
                //item = ctx.Talent.Add(new Talent()
                //{
                //    Recruiter = userName,
                //    ResumeId = resumeId
                //});
                //if (ctx.SaveChanges() > 0)
                //{
                //    Covariant(item);
                //    return this;
                //}
                //return null;
            }
        }
        public bool RemoveTalent(int id)
        {
            using (Context ctx = new Context())
            {
                return ctx.Delete<Talent>()
                    .WhereSet(c => c.Id, WhereOperator.Equal, id)
                    .End()
                    .Excute() > 0;
                //return new Talent(id).PostDelete() > 0;
            }
        }
        public ItemListBox<TalentModel> QueryOfTalent(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.Talent
                            join r in ctx.ResumeSheet
                                on c.ResumeId equals r.Id
                            where c.Recruiter == UserName
                            orderby c.Id descending
                            select new { c, r })
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new TalentModel()
                           {
                               Id = c.c.Id,
                               Recruiter = c.c.Recruiter,
                               Resume = new ResumeSheetModel()
                               {
                                   Title = c.r.Title,
                                   Address = c.r.Address,
                                   Age = c.r.Age,
                                   Area = (AreaCode)c.r.Area,
                                   ContactPhone = c.r.ContactPhone,
                                   Gender = c.r.Gender ? Gender.Male : Gender.Female,
                                   Id = c.r.Id,
                                   RealName = c.r.RealName,
                                   Status = (SocialRole)c.r.Status,
                                   UserName = c.r.UserName
                               }
                           })
                           .ToList();
                ItemListBox<TalentModel> result = new ItemListBox<TalentModel>(list);
                result.BuildPage(ctx.Talent.Count(c => c.Recruiter == UserName),
                    page, pageSize);
                return result;

            }
        }
        #endregion

        #region 代理企业
        public DepositCompanyModel GetDepositCompany(int id)
        {
            return new DepositCompanyModel().Element(c => c.Id == id);
        }
        #endregion

       
    }
}
